#include "musiclist.h"
#include<QMimeDatabase>
#include<QSqlQuery>
#include<QSqlError>
MusicList::MusicList()
{

}

MusicList::MusicList(const QList<QUrl> &urlList)
{
    //对传进来的list进行创建music对象；
    for(auto&e:urlList)
    {
        //还需要对URL进行分析，是否为正确的文件；
        QMimeDatabase database;
       QMimeType mime =  database.mimeTypeForFile(e.toString());
       if(mime.name() == "audio/mpeg" || mime.name() == "audio/flac"||mime.name() == "audio/wav")
       {
           Music music(e);
           this->_musicList.push_back(music);
       }
    }

}


iterator MusicList::begin()
{
    return _musicList.begin();
}

iterator MusicList::end()
{
    return _musicList.end();
}

iterator MusicList::findId(const QString &musicId)
{
    for(auto it = begin();it!=end();it++)
    {
        if(it->getId() == musicId)
        {
            return it;
        }
    }
    return end();

}

void MusicList::writeToDB()
{
    //将歌曲信息写进数据库中；在程序退出时；
    for(auto music:_musicList)
    {
        music.insertMusicToDB();
    }
}

void MusicList::readFormDB()
{
    //从数据库中加载信息；
    QSqlQuery query("SELECT musicId, musicName, musicSinger, albumName,duration, musicUrl, isLike, isHistory FROM musicInfo");
    if(!query.exec())
    {
        qDebug()<<"查询失败"<<query.lastError().text();
        return;
    }
    while(query.next())
    {
        Music music;
        music.setMusicId(query.value(0).toString());
        music.setMusicName(query.value(1).toString());
        music.setMusicSinger(query.value(2).toString());
        music.setMusicAlbumn(query.value(3).toString());
        music.setMusicDuration(query.value(4).toLongLong());
        music.setMusicUrl(query.value(5).toString());
        music.setIsLike(query.value(6).toBool());
        music.setIsHistory(query.value(7).toBool());
        _musicList.push_back(music);
    }
}
